package com.videoaggre.zcl.ui.fragment.enterdesk

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.videoaggre.zcl.R
import com.videoaggre.zcl.api.ENTERDESK_SERVICE
import com.videoaggre.zcl.bean.EnterdeskImage
import com.videoaggre.zcl.common.ENTERDESK_IMAGE
import com.videoaggre.zcl.common.dp
import com.videoaggre.zcl.common.startKtxActivity
import com.videoaggre.zcl.common.toColor
import com.videoaggre.zcl.parse.impl.EnterdeskParse
import com.videoaggre.zcl.ui.activity.wallpaper.enterdesk.EnterdeskImageDetailActivity
import com.videoaggre.zcl.ui.adapter.ImageShowAdapter
import com.videoaggre.zcl.ui.fragment.BaseRefreshFragment
import com.videoaggre.zcl.ui.fragment.launchUI
import kotlinx.android.synthetic.main.enterdesk_fragment_image.*
import kotlinx.android.synthetic.main.view_refresh.*

open class EnterdeskImageFragment(layoutResID: Int? = R.layout.enterdesk_fragment_image) : BaseRefreshFragment<EnterdeskImage>(layoutResID) {
    protected val mImageShowAdapter = ImageShowAdapter()
    override fun initView(rootView: View?, savedInstanceState: Bundle?) {
        bindViewClick(ivToUp)
        mImageShowAdapter.setOnClickAdapterListenter(::onClick)
        mBaseRecyclerAdapter = mImageShowAdapter
        super.initView(rootView, savedInstanceState)
        recyclerView.layoutManager = StaggeredGridLayoutManager(2, RecyclerView.VERTICAL).apply { gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE }
        refreshLayout.apply {
            setBackgroundColor(R.color.white.toColor())
            setEnableAutoLoadMore(true)
            setDisableContentWhenLoading(false)
            setDisableContentWhenRefresh(false)
        }
        recyclerView.setPadding(3.dp, (-3).dp, 3.dp, 3.dp)
    }

    override fun onClick(v: View?) {
        when (v) {
            ivToUp -> recyclerView.scrollToPosition(0)
        }
    }

    open fun onClick(view: View, position: Int) {
        startKtxActivity<EnterdeskImageDetailActivity>(value = ENTERDESK_IMAGE to mImageShowAdapter.getItem(position))
    }

    override fun onReload() {
        launchUI({ EnterdeskParse.parseImages(ENTERDESK_SERVICE.recommend(if (mRefreshHelper.page == 1) "" else "${mRefreshHelper.page}.html")) }, mRefreshHelper.handApiObserver())
    }
}